package com.liuceng.peatio.service

import com.liuceng.BaseSpec
import com.liuceng.peatio.model.FrontCampaign
import com.liuceng.peatio.utils.RedisUtils
import org.springframework.beans.factory.annotation.Autowired
import redis.clients.jedis.Jedis
import redis.clients.jedis.JedisPool

import static spock.util.matcher.HamcrestMatchers.closeTo
import static spock.util.matcher.HamcrestSupport.that

/**
 * Created by liyuhang on 2016-13-11.
 */
class FrontCampaignServiceSpec extends BaseSpec {
    @Autowired
    JedisPool jedisPool
    Jedis jedis

    def setup() {
        jedis = jedisPool.getResource()
        jedis.flushDB()
    }

    def "test .getChargeBudgetAndBid from db"() {
        given:
        SelfOperationService selfOperationService = Stub(SelfOperationService) {
            updateSelfOperationBudgetAndBid(_) >> {}
        }

        FrontCampaignService campaignService = new FrontCampaignService(jedisPool: jedisPool, selfOperationService: selfOperationService)
        FrontCampaign campaign = new FrontCampaign(id: 1, memberId: 1, campaignType: 1, dayBudget: new BigDecimal(1000.24), adOffer: new BigDecimal(1.5))

        when:
        BigDecimal[] budgetAndBid = campaignService.getChargeBudgetAndBid(campaign)

        then:
        that budgetAndBid[0], closeTo(1000, 0.25)

        and:
        that budgetAndBid[1], closeTo(1, 0.5)
    }

    def "test .getChargeBudgetAndBid from redis"() {
        given:
        SelfOperationService selfOperationService = Stub(SelfOperationService) {
            updateSelfOperationBudgetAndBid(_) >> {}
        }
        FrontCampaign campaign = new FrontCampaign(id: 1, memberId: 1, campaignType: 1, dayBudget: new BigDecimal(1000.24), adOffer: new BigDecimal(1.5))

        String key = RedisUtils.buildMemberBudgetAndBidKey(campaign.getMemberId(), campaign.getCampaignType())
        jedis.set(key, "1000.23:2.87")
        FrontCampaignService campaignService = new FrontCampaignService(jedisPool: jedisPool, selfOperationService: selfOperationService)

        when:
        BigDecimal[] budgetAndBid = campaignService.getChargeBudgetAndBid(campaign)

        then:
        that budgetAndBid[0], closeTo(1000, 0.24)

        and:
        that budgetAndBid[1], closeTo(2, 0.88)
    }
}